package com.morequick.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.morequick.model.Category;
import com.morequick.model.Product;
import com.morequick.service.CategoryService;
import com.morequick.service.ProductService;
import com.morequick.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/admin/product")
public class ProductControler {

    @Resource
    private ProductService productService;

    @Resource
    private CategoryService categoryService;

    /**
     * 商品首页
     *
     * @return
     */
    @RequestMapping("/index")
    public String index(ModelMap model, HttpServletRequest request) throws ParseException {
        String pageSize = request.getParameter("pageSize");
        String name = request.getParameter("name");
        String isTop = request.getParameter("is_top");
        String initTime = request.getParameter("init_time");
        String endTime = request.getParameter("end_time");
        if (pageSize == null) {
            pageSize = "1";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("isTop", isTop);
        params.put("initTime", initTime);
        params.put("endTime", endTime);
        PageHelper.startPage(Integer.parseInt(pageSize), 8);
        List<Product> products = productService.getProduct(params);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date data = null;
        String format = null;
        for (Product product : products) {
            data = dateFormat.parse(product.getCreatedAt());
            format = dateFormat.format(data);
            product.setCreatedAt(format);
        }
        PageInfo<Product> page = new PageInfo<>(products);
        StringBuilder sb = new StringBuilder();
        sb.append("&name=" + (name != null ? name : ""));
        sb.append("&init_time=" + (initTime != null ? initTime : ""));
        if (isTop != null && isTop != "") {
            sb.append("&is_top=" + (isTop != null ? isTop : ""));
        }
        sb.append("&end_time=" + (endTime != null ? endTime : ""));
        String url = sb.toString();
        model.addAttribute("products", page);
        model.addAttribute("url", url);
        model.addAttribute("params", params);
        return "/admin/product/index";
    }

    @RequestMapping("/create")
    public String create(ModelMap model) {
        List<Category> categories = categoryService.getCategory();
        model.addAttribute("categories", categories);
        return "/admin/product/create";
    }


    @RequestMapping(value = "/store", method = RequestMethod.POST)
    public String store(@RequestParam("file") MultipartFile file, Product product, @RequestParam(value = "category_id") int category_id, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String urlImg = this.upload(file, response, request);
        Category category = new Category();
        category.setId(category_id);
        if (product.getIsTop() == null) {
            product.setIsTop(0);
        }
        product.setCategory(category);
        product.setThumb(urlImg);
        productService.add(product);
        return "redirect:/admin/product/index";
    }

    @RequestMapping(value = "/edit")
    public ModelAndView edit(@RequestParam("id") Integer id) {
        ModelAndView mav = new ModelAndView();
        List<Category> categories = categoryService.getCategory();
        Product product = productService.findById(id);
        mav.addObject("product", product);
        mav.addObject("categories", categories);
        mav.setViewName("admin/product/edit");
        return mav;
    }

    @RequestMapping(value = "/update")
    public String update(@RequestParam("file") MultipartFile file, Product product, @RequestParam(value = "category_id") int category_id, @RequestParam("id") Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String urlImg = this.upload(file, response, request);
        Category category = new Category();
        category.setId(category_id);
        product.setId(id);
        if (product.getIsTop() == null) {
            product.setIsTop(0);
        }
        product.setCategory(category);
        product.setThumb(urlImg);
        productService.update(product);
        return "redirect:/admin/product/index";
    }

    @RequestMapping(value = "/delete")
    public String delete(@RequestParam("id") Integer id) {
        productService.delete(id);
        return "redirect:/admin/product/index";
    }


    @RequestMapping(value = "/isSomething", method = RequestMethod.POST)
    public String isSomething(@RequestBody Map<String, Object> params, HttpServletResponse response) throws Exception {
        Integer id = Integer.valueOf(params.get("id").toString());
        String attr = params.get("attr").toString();
        // 操作的记录条数
        Product product = productService.findById(id);
        if (product.getIsOnsale() == 1) {
            product.setIsOnsale(0);
        } else if (product.getIsOnsale() == 0) {
            product.setIsOnsale(1);
        }
        int resultTotal = productService.update(product);
        JSONObject result = new JSONObject();
        if (resultTotal > 0) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping(value = "/destroyChecked", method = RequestMethod.POST)
    public String destroyChecked(@RequestBody Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<String> idList = (List<String>) params.get("id");
        Integer count = productService.deleteAd(idList);
        JSONObject result = new JSONObject();
        if (count > 0) {
            result.put("message", "删除成功");
            result.put("success", true);
        } else {
            result.put("error", false);
        }
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping(value = "/sortOrder", method = RequestMethod.POST)
    public String sortOrder(@RequestBody Map<String, Object> params, HttpServletResponse response) throws Exception {
        Integer id = Integer.valueOf(params.get("id").toString());
        Integer sort = Integer.valueOf(params.get("sort").toString());
        JSONObject result = new JSONObject();
        if (sort <= 0) {
            result.put("message", "不能小于1");
            result.put("error", false);
            ResponseUtil.write(response, result);
            return null;
        }

        // 操作的记录条数
        Product product = productService.findById(id);
        product.setSortOrder(sort);
        Integer count = productService.update(product);
        if (count > 0) {
            result.put("message", "排序成功");
            result.put("success", true);
        } else {
            result.put("error", false);
        }
        ResponseUtil.write(response, result);
        return null;
    }


    private String upload(MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (file.getSize() < 1) {
            ResponseUtil.write(response, "文件不能为空");
            return "/admin/product/create";
        }

        String fileName = file.getOriginalFilename();
        //文件保存目录路径
        String savePath = request.getServletContext().getRealPath("/");

        //文件保存目录URL
        String saveUrl = request.getContextPath();

        //String fileName =file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");

        HashMap<String, Object> result = new HashMap<String, Object>();

        if (!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)) {

            result.put("error", "只允许" + extMap.get("image") + "格式。");

            ResponseUtil.write(response, result);

            return null;
        }

        if (file.getSize() > 1000000) {

            result.put("error", "文件过大");

            ResponseUtil.write(response, result);

            return null;
        }

        String dirName = request.getParameter("file");
        if (dirName == null) {
            dirName = "/images";
        }

        //创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        String urlImg = saveUrl + newFileName;
        file.transferTo(uploadedFile);
        return urlImg;

    }


}
